package p2pscrabble;

import java.net.*;
import java.io.*;

// class declaration of Connection
class Connection {

	Socket socket = null; // the actual socket Connection
	private BufferedReader in;
	private PrintWriter out;

	public Connection(Socket socket) {
		try {
			this.socket = socket;
			in = new BufferedReader(new InputStreamReader(this.socket
					.getInputStream()));
			out = new PrintWriter(this.socket.getOutputStream(), true);
		} catch (IOException e) {
		}
	}

	public void send_data(String data) {
		out.print(data + "\n");
		out.flush();
	}

	public String receive_data() {
		String s = null;
		try {
			s = in.readLine();
		} catch (IOException e) {
		}
		if (s == null)
			s = "";
		return s;
	}

	public void send_game_state(String data) {
		send_data(data.replaceAll("\n", "<newline>"));
	}
	
	public String receive_game_state() {
		String s = receive_data();
		return s.replaceAll("<newline>", "\n");
	}

	public void wait_for_data() {
		try {
			while (!in.ready()) {
				// do nothing
				try {
					// Poll every ~10 ms
					Thread.sleep(20);
				} catch (InterruptedException e) {
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public boolean isConnected() {
		return socket.isConnected();
	}

}
